package utils

import (
	"crypto/md5"
	"encoding/hex"
	"io"
	"os"
	"path/filepath"
)

// CreateDir 创建目录
func CreateDir(path string, perm os.FileMode) error {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		if err = os.MkdirAll(path, perm); err != nil {
			return err
		}
	} else if err != nil {
		return err
	}

	return nil
}

func CopyFileTOMD5Named(src, destDir string) (string, error) {
	sourceFile, err := os.Open(src)
	if err != nil {
		return "", err
	}

	// 获取源文件的文件名
	sourceInfo, err := sourceFile.Stat()
	if err != nil {
		return "", err
	}
	fileName := sourceInfo.Name()

	//创建目标文件
	destinationFilePath := filepath.Join(destDir, fileName)
	destinationFile, err := os.Create(destinationFilePath)
	if err != nil {
		return "", err
	}

	//计算文件md5
	hash := md5.New()
	multiWriter := io.MultiWriter(destinationFile, hash)

	_, err = io.Copy(multiWriter, sourceFile)
	if err != nil {
		return "", err
	}

	hashInBytes := hash.Sum(nil)
	md5String := hex.EncodeToString(hashInBytes)
	//关闭句柄
	if sourceFile.Close() != nil || destinationFile.Close() != nil {
		return "", nil
	}

	destinationFilePathWithMD5 := filepath.Join(destDir, md5String+filepath.Ext(fileName))
	err = os.Rename(destinationFilePath, destinationFilePathWithMD5)
	if err != nil {
		return "", err
	}

	return destinationFilePathWithMD5, nil
}

// CopyFile 复制文件
func CopyFile(src, dest string) error {
	sourceFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer sourceFile.Close()

	destinationFile, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer destinationFile.Close()

	_, err = io.Copy(destinationFile, sourceFile)
	if err != nil {
		return err
	}

	return nil

}

// CopyFileToDir 复制文件到路径
func CopyFileToDir(src, destDir string) error {
	sourceFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer sourceFile.Close()

	// 获取源文件的文件名
	sourceInfo, err := sourceFile.Stat()
	if err != nil {
		return err
	}
	fileName := sourceInfo.Name()

	destinationFilePath := filepath.Join(destDir, fileName)
	destinationFile, err := os.Create(destinationFilePath)
	if err != nil {
		return err
	}
	defer destinationFile.Close()

	_, err = io.Copy(destinationFile, sourceFile)
	if err != nil {
		return err
	}

	return nil

}

// FileExists 文件是否存在
func FileExists(filename string) bool {
	_, err := os.Stat(filename)
	return !os.IsNotExist(err)
}
